package com.oneinlet.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Map;

/**
 * Created by WangZiHe on 2018/6/9
 * QQ/WeChat:648830605
 * QQ-Group:368512253
 * Blog:www.520code.net
 * Github:https://github.com/yancheng199287
 */
public class LoggerHandlerInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(getClass());


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) {

        //logger.info("LoggerHandlerInterceptor-----preHandle:");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object, ModelAndView modelAndView) {

        //logger.info("LoggerHandlerInterceptor-----postHandle:");

    }

    @SuppressWarnings("rawtypes")
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object, Exception e) {

        if (!(object instanceof HandlerMethod)) {
            return;
        }

        logger.info("--------start----------日志监控拦截正在捕获网络请求----------------");
        HandlerMethod handlerMethod = (HandlerMethod) object;
        String methodName = handlerMethod.getMethod().getName();
        String className = handlerMethod.getBeanType().getName();
        int status = httpServletResponse.getStatus();
        String browser = httpServletRequest.getHeaders("User-Agent").nextElement();
        String url = httpServletRequest.getRequestURI();
        logger.info("当前浏览器是：" + browser);
        logger.info("获取当前的session id ：" + httpServletRequest.getSession().getId());
        logger.info("获取当前访问的主机 ip ：" + httpServletRequest.getRemoteAddr());
        logger.info("当前访问的url ：" + url);
        logger.info("调用的类名：" + className + ", 调用方法名：" + methodName);
        logger.info(getRequestParams(httpServletRequest));
        logger.info("获取http状态码：" + status);
        logger.info("--------end----------日志监控拦截正在捕获网络请求----------------");
    }

    private String getRequestParams(HttpServletRequest request) {
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
            stringBuilder.append("\n").append("---> 请求参数列表：").append("key:").append(entry.getKey()).append(" value:").append(Arrays.toString(entry.getValue()));
        }
        return stringBuilder.toString();
    }
}
